<template>
<div v-bind:id="charterId">

  <div class='gridster' width="100%" height="90%" :style="charterStyle">
    <ul></ul>
  </div>

</div>
</template>

<script>
import chartLoader from 'common/graph/chartLoader'
import api from 'api/graph'
import print from 'utils/print.js'

export default {
  props: {
    parentDesignerData: {
      type: Object,
      default: function() {
        return {
          grsName: '',
          grsNo: '',
          remark: ''
        }
      }
    },
    charterId: {
      type: String,
      default: function() {
        return 'charterOne'
      }
    },
    charterStyle: {
      type: Object,
      default: function() {
        return {}
      }
    },
    inputParams: { //外部传入参数
      type: Object,
      default: function() {
        return {}
      }
    },
    thisParams:{
      type: String,
      default: function() {
        return ''
      }
    },
    thisParamKey:{
      type: String,
      default: function() {
        return ''
      }
    }
  },
    data: function() {
        return {
        };
    },
    methods: {
      init(){
        //初始化加载数据
        if (this.parentDesignerData.grsNo) {
          //关联外部传入数据
          this._initContainer();
          this.loadConfig(this.parentDesignerData.grsNo);
        } else {
          this.$grid = $("#" + this.charterId + " .gridster");
          this.setEmptyShow();
        }
      },
      _initContainer() {
        var self = this;
        var $grid = $("#" + this.charterId + " .gridster");
        this.$grid = $grid;
        chartLoader.clearTimer($grid);
        this.gridster = null;

        //actual为自定义扩展方法，用于获取隐藏元素的宽度，在jquery.gridster.js中注册的
        var winWidth = $grid.actual('width');
        var setWidth = Math.floor((winWidth - 70) / 7);

        $grid.html('<ul></ul>');

        var winHeight = $grid.parent().height();
        var setHeight = Math.floor((winHeight - 150) / 15);
        var setOption = { //通过jquery选择DOM实现gridster
          widget_base_dimensions: [setWidth, setHeight], //模块的宽高 [宽,高]
          widget_margins: [5, 5], //模块的间距 [上下,左右]
          min_cols: 7,
          min_rows: 15,
          resize: {
            enabled: 'true', //允许放缩
            handle: '.resize', //html标签的css类名，按住此标签可以对网格进行放缩
            axes: ['x', 'y', 'both'],
            stop: function(event, ui) { //结束时重新加载数据
              var $li = $(ui.$helper).parents("li");
              self._loadChart($li, $li.data("form"));
            }
          },
          serialize_params: function($w, wgd) { //$w为要输出位置的网格对象（li），wgd为该网格对象的坐标对象，包括col，row，size                                                     //_x,size_y四个成员
            return {
              col: wgd.col,
              row: wgd.row,
              size_x: wgd.size_x,
              size_y: wgd.size_y,
              form: $w.data("form") //存储的表单信息
            }
          },
          draggable: {
            handle: 'div.graph-header', //头部拖动
            stop: function(event, ui) {

            }
          }
        };
        var gridster = $grid.find("ul").gridster(setOption).data('gridster');

        this.gridster = gridster;

        $grid.on('click', '.gs-refresh', function() {
          var $li = $(this).parents("li");
          self._loadChart($li, $li.data("form"));
        });
         //点击打印图形
         print.bindEvent($grid)
      },
      loadConfig(grsNo) {
        //读取配置信息
        api.getGraphConfig(grsNo).then((response) => {
          if (response.data) {
            var rdata = response.data
            this._loadGridster(eval('' + rdata["widgetData"] + ''));
          }
        }).catch((err) => {
          console.error(err);
        });
      },
      _loadGridster(initData) {
        var self = this;
        this.cleanAll();
        if (initData) {
          //注意：Gridster首字母必须大写；先按row排序，row相同的再按列排序，按排序后的顺序插入data可以保证位置不会偏移
          var data = self.Gridster.sort_by_row_and_col_asc(initData);
          //alert("排序后的widget:\n" + JSON.stringify(data));
          for (var i = 0; i < data.length; i++) {
            var wrapper = this._createLi();
            self.gridster.add_widget(wrapper, data[i].size_x, data[i].size_y, data[i].col, data[i].row);
            self._loadChart(wrapper, data[i]["form"]);
          }
        }
      },
      _loadChart($el, form) {
        $el.data("form", form);

        //获取公共参数
        var params = $.extend({}, this.inputParams);
        //获取当前参数
        if(this.thisParams!=""){
          var obj = eval("("+this.thisParams+")");
          var nowParams = obj[this.thisParamKey];
          params = $.extend({}, nowParams);
        }
        chartLoader._init($el, form, params);
        //加载一个图表之后，清除无数据标记
        this.$grid.find(".empty-graph").remove();
      },
      _createLi() {
        var wrapper = $('<li></li>');
        wrapper.append('<a href="javascript:;" class="gs-refresh" title="刷新"><i class="el-icon-refresh"></i></a>');
        //打印按钮
        // let a40 = '<a href="javascript:;" class="gs-print" style="position: absolute;top: 5px;right: 40px;font-size: 10px;display: inline;z-index: 9999" title="打印"><i class="el-icon-document"></i></a>'
        // let a55 = '<a href="javascript:;" class="gs-print" style="position: absolute;top: 5px;right: 55px;font-size: 10px;display: inline;z-index: 9999" title="打印"><i class="el-icon-document"></i></a>'
        let a40 = print.createElement(40)
        let a55 = print.createElement(55)
        //是否可以编辑
        if (this.editable) {
          wrapper.append('<a href="javascript:;" class="gs-edit" style="display: inline;"title="编辑"><i class="el-icon-edit"></i></a>' +
            '<a href="javascript:;" class="gs-close" style="" title="关闭"><i class="el-icon-close" ></i></a>');
          wrapper.append(a55);
        }else{
          wrapper.append(a40);
        }

        //添加内容模块
        wrapper.append('<div class="chart" style="height: 100%;width: 100%;text-align:center">' +
          '<div class="graph-header" style="cursor:move"></div>' +
          '<div class="graph-bodyer"></div>' +
          '<div class="graph-footer"></div></div>');
        return wrapper;
      },
      _addWidget(form, $li) {
        //添加节点
        if (!$li) {
          $li = this._createLi();
          if (!this.gridster) {
            this._initContainer();
          }
          this.gridster.add_widget($li, 1, 5);
        }
        this._loadChart($li, form);
      },
      cleanAll() {
        chartLoader.clearTimer(this.$grid); //清除定时器
        if (this.gridster) {
          this.gridster.remove_all_widgets(null);
          this.setEmptyShow();
        }
      },
      setEmptyShow() {
            if (!this.gridster || !this.gridster.hasWidget()) {
              this.$grid.find("ul").html('<div class="empty-graph el-table__empty-block" style="width: ' + this.$grid.actual('width') + 'px;"><span class="el-table__empty-text">' + ((this.editable) ? '暂无图形' : '等待载入') + '</span></div>');
            }
      },
      //窗口重置监听
      resizeListen(){
        const self = this;
        var resizeTimer = null;
        $('section').resize(function() {
          //如果界面上已经不存在图形，取消时间监控
          if ($('.gridster').length == 0) {
            $('section').unbind("resize");
            return false;
          }
          if (resizeTimer) clearTimeout(resizeTimer);
          resizeTimer = setTimeout(function() {
            self.init();
          }, 500);
        });
      }
    },
    mounted(){
      this.Gridster = require("gridster"); //引入模块，在webpack.base.conf.js中注册的
      var self = this;
      //初始化设计器
      this.init();
      //
      this.resizeListen();
    }
}
</script>
